require 'common.tcpAgent'
local skynet = require "skynet"
local protobuf = require 'protobuf'
loginAgent = class('loginAgent', tcpAgent)

function loginAgent:ctor()
    self.playerId = nil
    self.avatar = nil
end

function loginAgent:REGISTER(message)
    local register, reason = protobuf.decode('RegisterReq', message)
    if reason then
        skynet.error('loginAgent:REGISTER', reason)
        return false, 'FAILED'
    end

    local username = register.username
    local pwd = register.password
    local ok, err = skynet.call('loginManager', 'lua', 'Register', username, pwd)
    if ok then
        return true, protobuf.encode("RegisterResp", {})
    else
        return false, 'FAILED'
    end
end

function loginAgent:LOGIN(message)
    local login, reason = protobuf.decode('LoginReq', message)
    if reason then
        skynet.error('loginAgent:LOGIN', reason)
        error('FAILED')
    end

    --local username = login.username
    --local pwd = login.password
    --local ok, playerId = skynet.call('loginManager', 'lua', 'Auth', username, pwd)
    --if not ok then
    --    error('FAILED')
    --end

    self.playerId = os.time()
    local avatar, conv = skynet.call('avatarManager', 'lua', 'CreateAvatar', skynet.self(), self.playerId)
    self.avatar = avatar
    return true, protobuf.encode("LoginResp", {playerId = self.playerId, conv = conv})
end

function loginAgent:RECONNECT(message)
    local reconnect, reason = protobuf.decode('ReconnectReq', message)
    if reason then
        skynet.error('loginAgent:RECONNECT', reason)
        error('FAILED')
    end

    local playerId = reconnect.playerId
    local conv = reconnect.conv
    local ok, avatar = skynet.call('avatarManager', 'lua', 'Reconnect', skynet.self(), playerId, conv)
    if ok then
        self.playerId = playerId
        self.avatar = avatar
        return protobuf.encode("ReconnectResp", {})
    else
        error('FAILED')
    end
end

function loginAgent:OnDisconnect()
    if self.avatar then
        skynet.call(self.avatar, 'lua', 'OnLoginAgentDisconnect', skynet.self())
    end
    self.avatar = nil
end

agent = loginAgent.new()
agent:Start()